package com.owen.java.demo.quartz.listener;

import org.quartz.*;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class DependencyJobListener implements JobListener {
    private final Map<JobKey, Set<JobKey>> dependencyMap = new ConcurrentHashMap<>();
    private final Map<JobKey, Set<JobKey>> completedMap = new ConcurrentHashMap<>();

    public void addDependency(JobKey child, JobKey parent) {
        dependencyMap.computeIfAbsent(child, k -> ConcurrentHashMap.newKeySet()).add(parent);
        completedMap.computeIfAbsent(child, k -> ConcurrentHashMap.newKeySet());
    }

    @Override
    public String getName() {
        return "dependency";
    }

    @Override
    public void jobToBeExecuted(JobExecutionContext context) {

    }

    @Override
    public void jobExecutionVetoed(JobExecutionContext context) {

    }

    @Override
    public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
        JobKey completedJob = context.getJobDetail().getKey();

        // 检查哪些子任务依赖这个已完成的任务
        dependencyMap.forEach((child, parents) -> {
            if (parents.contains(completedJob)) {
                completedMap.get(child).add(completedJob);

                // 如果所有依赖都完成了
                if (completedMap.get(child).containsAll(parents)) {
                    try {
                        context.getScheduler().triggerJob(child);
                        completedMap.get(child).clear(); // 重置状态
                    } catch (SchedulerException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    // 其他必要的方法实现...
}
